package com.bmft.ftcloud.controller;

import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.bmft.ftcloud.config.RedisConfig;
import com.bmft.ftcloud.mapper.SysUserMapper;
import com.bmft.ftcloud.model.constant.Constant;
import com.bmft.ftcloud.model.entity.SysUser;
import com.bmft.ftcloud.service.MailService;
import com.bmft.ftcloud.service.RedisService;
import com.bmft.ftcloud.util.redis.RandomUtil;
import com.bmft.ftcloud.util.response.Result;
import com.bmft.ftcloud.util.token.TokenUtil;
import com.fasterxml.jackson.datatype.jsr310.ser.YearSerializer;
import com.mysql.cj.xdevapi.JsonArray;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.SqlParameterSourceUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.swing.text.EditorKit;

import java.util.HashMap;
import java.util.Map;

import static com.bmft.ftcloud.util.response.Result.*;

/**
 * @author Jarvan
 * @version 1.0
 * @create 2020/11/28 12:56
 */
@Slf4j
@CrossOrigin("http://localhost:8080")
@RestController()
@RequestMapping("/user/*")
public class UserController {
    @Autowired
    SysUserMapper sysUserMapper;
    @Autowired
    TokenUtil tokenUtil;
    @Autowired
    MailService mailService;
    @Autowired
    RedisService redisService;


    @PostMapping("/login")
    public Result<Map<String, String>> login(@RequestParam String username,
                                             @RequestParam String password,
                                             HttpServletRequest request,
                                             HttpServletResponse response) {
        log.info("login======");
        //这里使用条件构造器.构造查询函数，就不用SQL了.
        QueryWrapper<SysUser> query = new QueryWrapper<>();
        query.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(query);
        if (sysUser.getPassword().equals(password)) {
            //将加密后的token放到map 里面并返回。
            String ip = request.getHeader("Host");
            HashMap<String, String> map = new HashMap<String, String>();
            map.put(Constant.TOKEN, tokenUtil.getToken(username, sysUser.getRoleCode(), ip));
            map.put("roleName", sysUser.getRoleName());
            map.put("username", sysUser.getUsername());
            map.put("password", "******");
            map.put("nickname", sysUser.getNickname());
            map.put("email", sysUser.getEmail());
            return success(map);
        }
        return fail(null);

    }

    @PostMapping("/logout")
    public Result<String> logout(HttpServletResponse response) {

        return success("退出成功");
    }

    @PostMapping("/register")
    public Result<String> register(@RequestBody JSONObject json) {
        String emailConfirm = (String) json.get("emailConfirm");
        String password = (String) json.get("password");
        String roleName = (String) json.get("roleName");
        String nickname = (String) json.get("nickname");
        String email = (String) json.get("email");
        String username = (String) json.get("username");
        String roleCode = (String) json.get("roleCode");
        //匹配验证码是否正确
        String autoCodeOfEmail = (String) redisService.get(email);
        if (autoCodeOfEmail.equals(emailConfirm)) {
            //销毁redis验证码.
            redisService.delete(email);
            SysUser sysUser = new SysUser(username, password, email, roleCode, roleName, nickname);
            int insert = sysUserMapper.insert(sysUser);
            if (insert > 0) {
                return success("验证码匹配");
            }
            return fail("注册失败");
        }
        return fail("验证码不匹配");
    }

    @PostMapping("/updateInfo")
    public Result<String> updateInfo(@RequestBody JSONObject json) {
        String emailConfirm = (String) json.get("emailConfirm");
        String password = (String) json.get("password");
        String nickname = (String) json.get("nickname");
        String email = (String) json.get("email");
        String username = (String) json.get("username");
        //调用redis. 验证验证码.
        //移除验证码redis.
        String autoCodeOfEmail = (String) redisService.get(email);
        redisService.delete(email);
        if (autoCodeOfEmail.equals(emailConfirm)) {
            //验证角色
            QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
            wrapper.eq("username",username);
            SysUser sysUser = sysUserMapper.selectOne(wrapper);
            sysUser.setNickname(nickname);
            //修改了密码才后端才能改密码
            if (!password.contains("*")){
                sysUser.setPassword(password);
            }
            int update = sysUserMapper.update(sysUser, null);
            if (update > 0) {
                return success("修改成功");
            }
        }
        return fail("修改失败");
    }

    @PostMapping("/usernameConfirm")
    public Result<String> usernameConfirm(@RequestParam("username") String username) {
        QueryWrapper<SysUser> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        SysUser sysUser = sysUserMapper.selectOne(wrapper);
        if (sysUser != null) {
            return Result.fail("账户已经存在");
        }
        return success("该账户可以注册");
    }

    @PostMapping("/emailConfirm")
    public Result<String> emailConfirm(@RequestParam("email") String email) {
        log.info("======邮件:"+email+"==========");
        //获得随机码
        String authCode = "" + RandomUtil.getSixRandomCode();
        //异步发送邮件通知
        mailService.accountAuthentication(email, authCode);
        //异步储存到redis.
        redisService.set(email, authCode);
        return Result.success("发送成请查收");
    }

    @PostMapping("/test")
    public Result<String> test() {
        return success("test");
    }
}
